/**
 * Created by chang on 2017/2/9.
 */
const _push = module.exports

const amqp_cfg = configure.get('amqp')

const im_suffix = amqp_cfg.im_suffix || ''
const im_task_queue = amqp_cfg.im_task_queue + im_suffix

const amqp = require('amqp-connection-manager-rpcx')
const connection = amqp.connect([amqp_cfg.url], { json: true })

const channelWrapper = connection.createRPCClient(im_task_queue, 60, async (channel)=>{
    return await channel.assertQueue(`rpc.im.task.${helper.uuid_short()}`, { exclusive: true, durable: false, autoDelete: true});
})

channelWrapper.on('connect', function () {
    log4js.debug('RPC Client connection Connected!')
})
channelWrapper.on('disconnect', function (params) {
    log4js.error('RPC Client connection Disconnected.', params.err.stack)
})

_push.post_message = async (req, res) => {
    let { notice_receiver, way, content_type, content, org_id } = req.body

    if (!_.isArray(notice_receiver)) notice_receiver = [notice_receiver]
    if (_.isEmpty(notice_receiver)) return res.jsonWrap(null, 1, 'notice_receiver can not be empty')
    if (!_.isNumber(content_type)) return res.jsonWrap(null, 1, 'content_type must be number')
    if (_.isEmpty(content)) return res.jsonWrap(null, 1, 'content can not be empty')
    if (!_.isObject(way)) return res.jsonWrap(null, 1, 'way must be object')
    if (!_.get(way, 'way_code')) return res.jsonWrap(null, 1, 'way.way_code can not be empty')

    let _way_info = await dbUtil.getRow('dic_notice_way', { way_code: _.get(way, 'way_code') })

    if (!_way_info) return res.jsonWrap(null, 1, 'way_code is not exist')

    let _task = await M('notice_task').create({
        id: helper.uuid(),
        service_info: req.jwt,
        notice_receiver,
        way,
        content_type,
        org_id: org_id || '',
        content
    })

    try {
        let _task_result = await channelWrapper.sendRPC(_task._doc)
        let _task_detail = await dbUtil.getAll('notice_task_detail', { notice_task_id: _task_result.id })

        return res.jsonWrap({
            ..._task_result,
            task_detail: _task_detail,
        }, 0, '消息发送成功')

    } catch (e) {
        log4js.error(e)
        return res.jsonWrap(null, 1, e.message)
    }
}
